<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace CZTools\Hyperf\Exceptions\Handler;


use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Validation\ValidationException;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ValidationExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
//      判断被捕获到的异常是希望被捕获的异常
        $error_msg = '';

        if ($throwable instanceof ValidationException) {
            if (!$response->hasHeader('content-type')) {
                $response = $response->withAddedHeader('content-type', 'text/json; charset=utf-8');
            }

            /** @var \Hyperf\Validation\ValidationException $throwable */
            $error_msg = $throwable->validator->errors()->first();
        }

        if ($error_msg) {
            // 格式化输出
            $data = json_encode([
                'code' => 10000,
                'message' => $error_msg,
            ], JSON_UNESCAPED_UNICODE);

            // 阻止异常冒泡
            $this->stopPropagation();
            $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
            $this->logger->error($throwable->getTraceAsString());

            return $response->withStatus(200)->withBody(new SwooleStream($data));
        }

        // 交给下一个异常处理器
        return $response;

        // 或者不做处理直接屏蔽异常
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof ValidationException;
    }
}
